package cn.tedu.loding.service.impl;

import cn.tedu.loding.ex.ServiceException;
import cn.tedu.loding.mapper.*;
import cn.tedu.loding.pojo.dto.ProductAddNewDTO;
import cn.tedu.loding.pojo.dto.ProductUpdateDTO;
import cn.tedu.loding.pojo.entity.Product;
import cn.tedu.loding.pojo.vo.*;
import cn.tedu.loding.service.IProductService;
import cn.tedu.loding.web.ServiceCode;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 处理商品数据的业务实现类
 *
 * @author java@tedu.cn
 * @version 0.0.1
 */
@Slf4j
@Service
public class ProductServiceImpl implements IProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private AlbumMapper albumMapper;
    @Autowired
    private AttributeTemplateMapper attributeTemplateMapper;
    @Autowired
    private AttributeMapper attributeMapper;
    @Autowired
    private PictureMapper pictureMapper;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private CategoryMapper categoryMapper;


    public ProductServiceImpl() {
        log.debug("创建业务对象：productServiceImpl");
    }

    @Override
    public void addNew(ProductAddNewDTO productAddNewDTO) {
        log.debug("开始处理【添加商品】的业务，参数：{}", productAddNewDTO);
        // 从参数对象中获取商品名称
        String productName = productAddNewDTO.getName();
        // 检查商品名称是否已经被占用（商品表中是否已经存在此名称的数据）
        log.debug("检查商品名称是否已经被占用");
        {
            int count = productMapper.countByName(productName);
            if (count > 0) {
                // 是：商品名称已经被占用，添加商品失败，抛出异常
                String message = "添加商品失败，商品名称已经被占用！";
                log.debug(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }
        {
            BrandStandardVO brandStandardVO = brandMapper.getStandardById(productAddNewDTO.getBrandId());
            if (brandStandardVO == null) {
                // 品牌不存在
                String message = "添加商品失败，所选品牌不存在！";
                log.debug(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }
        {
            CategoryStandardVO categoryStandardVO = categoryMapper.getStandardById(productAddNewDTO.getCategoryId());
            if (categoryStandardVO == null) {
                // 类别不存在
                String message = "添加商品失败，所选类别不存在！";
                log.debug(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }
        // 否：商品名称没有被占用，则向商品表中插入数据
        log.debug("商品名称没有被占用，将向商品表中插入数据");
        Product product = new Product();
        BeanUtils.copyProperties(productAddNewDTO, product);
        product.setGmtCreate(LocalDateTime.now());
        product.setGmtModified(LocalDateTime.now());
        log.debug("即将插入商品数据：{}", product);
        int rows = productMapper.insert(product);
        if (rows != 1) {
            String message = "添加商品失败，服务器忙，请稍后再尝试！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("插入商品数据完成");
    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【根据id删除商品】的业务，参数：{}", id);
        // 调用Mapper对象的getStandardById()执行查询
        ProductStandardVO queryResult = productMapper.getStandardById(id);
        // 判断查询结果是否为null
        if (queryResult == null) {
            // 是：无此id对应的数据，将不允许执行删除操作，则抛出异常
            String message = "删除商品失败，尝试访问的数据不存在！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        // 检查是否存在图片（picture）关联到此商品，如果存在，则将该商品的相册一并删除
        {
            AlbumStandardVO albumStandardVO = albumMapper.getStandardByProductId(id);
            if (albumStandardVO != null) {
                String message = "有关联的相册数据，将删除该商品的相册";
                log.debug(message);
                log.debug("将删除相册id为{}的图片", albumStandardVO.getId());
                List<PictureStandardVO> list = pictureMapper.getStandardByAlbumId(albumStandardVO.getId());
                if (list != null) {
                    List<Long> pictureIds = new ArrayList<>();
                    for (PictureStandardVO item : list) {
                        pictureIds.add(item.getId());
                    }
                    log.debug("该商品的相册的图片id有{}", pictureIds);
                    int row = pictureMapper.deleteBatchByAlbumId(pictureIds);
                    log.debug("根据该商品的相册的图片id删除图片完成,删除的数据共有{}条", row);
                    albumMapper.deleteByProductId(id);
                }
                log.debug("删除该商品的相册数据完毕");
            }
        }
        // 检查是否存在属性模板（attributeTemplate）关联到此商品，如果存在，则将该商品的属性模板一并删除
        {
            List<AttributeTemplateStandardVO> list = attributeTemplateMapper.getStandardByProductId(id);
            if (list != null) {
                List<Long> attributeTemplateIds = new ArrayList<>();
                for (AttributeTemplateStandardVO item : list) {
                    attributeTemplateIds.add(item.getId());
                }
                log.debug("该商品的属性模板id有{}", attributeTemplateIds);
                int row = attributeMapper.deleteBatchByTemplateId(attributeTemplateIds);
                log.debug("根据该商品的属性模板id删除属性完成,删除的数据共有{}条", row);
            }
        }
        // 调用Mapper对象的deleteById()方法执行删除
        log.debug("即将执行删除，参数：{}", id);
        int rows = productMapper.deleteById(id);
        if (rows != 1) {
            String message = "删除商品失败，服务器忙，请稍后再尝试！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
    }

    @Override
    public void updateInfoById(ProductUpdateDTO productUpdateDTO) {
        log.debug("开始处理【修改商品详情】的业务， 新数据：{}" , productUpdateDTO);
        // 检查名称是否被占用
        {
            ProductStandardVO queryResult = productMapper.getStandardById(productUpdateDTO.getId());
            // 判断查询结果是否为null
            if (queryResult == null) {
                // 是：此id对应的数据不存在，则抛出异常(ERR_NOT_FOUND)
                String message = "修改商品详情失败，id无效！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
            }
        }
        {
            int count = productMapper.countByNameAndNotId(productUpdateDTO.getId(), productUpdateDTO.getName());
            if (count > 0) {
                String message = "修改商品详情失败，商品名称已经被占用！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }

        Product product = new Product();
        BeanUtils.copyProperties(productUpdateDTO, product);
        product.setId(productUpdateDTO.getId());
        product.setGmtModified(LocalDateTime.now());
        // 修改数据
        log.debug("即将修改数据：{}", product);
        int rows = productMapper.update(product);
        if (rows != 1) {
            String message = "修改商品详情失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

    @Override
    public ProductItemVO getStandardById(Long id) {
        log.debug("开始处理【根据id查询商品详情】的业务，参数：{}", id);
        ProductStandardVO product = productMapper.getStandardById(id);
        if (product == null) {
            String message = "获取商品详情失败，id无效！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        BrandStandardVO brandStandardVO = brandMapper.getStandardById(product.getBrandId());
        log.debug("根据品牌id【{}】查询到的品牌详情有{}", product.getBrandId(), brandStandardVO);

        CategoryStandardVO categoryStandardVO = categoryMapper.getStandardById(product.getCategoryId());
        log.debug("根据类别id【{}】查询类别详情有{}", product.getCategoryId(), categoryStandardVO);

        List<AttributeTemplateStandardVO> list = attributeTemplateMapper.getStandardByProductId(id);
        log.debug("该商品的属性模板有{}", list);
        if (list == null) {
            String message = "获取商品属性模板详情失败，id无效！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        List<String> attributeTemplateNames = new ArrayList<>();
        for (AttributeTemplateStandardVO item : list) {
            attributeTemplateNames.add(item.getName());
        }


        List<Long> attributeTemplateIds = new ArrayList<>();
        for (AttributeTemplateStandardVO item : list) {
            attributeTemplateIds.add(item.getId());
        }
        if (attributeTemplateIds.isEmpty()) {
            String message = "该商品属性模板不存在，请在属性模板和属性模块中添加！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        log.debug("该商品的属性模板id有{}", attributeTemplateIds);
        List<AttributeStandardVO> list1 = attributeMapper.getStandardByTemplateIds(attributeTemplateIds);
        log.debug("根据该商品的属性模板id查询属性完成,数据为:{}", list1);

        List<String> attributeNames = new ArrayList<>();
        for (AttributeStandardVO item : list1) {
            attributeNames.add(item.getName());
        }


        log.debug("开始处理根据商品id【{}】查询相册数据",id);
        AlbumStandardVO albumStandardVO = albumMapper.getStandardByProductId(id);
        if (albumStandardVO == null) {
            String message = "获取商品相册详情失败，id无效！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        List<PictureStandardVO>pictureList = pictureMapper.getStandardByAlbumId(albumStandardVO.getId());
        List<String>pictureUrls = new ArrayList<>();
        for (PictureStandardVO pictureItem:pictureList) {
            pictureUrls.add(pictureItem.getUrl());
        }
        log.debug("根据该商品的相册id查询图片完成,数据为:{}", pictureUrls);


        ProductItemVO productListVOS = new ProductItemVO();
        BeanUtils.copyProperties(product,productListVOS);
        productListVOS.setBrandName(brandStandardVO.getName());
        productListVOS.setCategoryName(categoryStandardVO.getName());
        productListVOS.setAlbumPicture(pictureUrls);
        productListVOS.setAttributeTemplateName(attributeTemplateNames);
        productListVOS.setAttributeName(attributeNames);
        log.debug("商品详情中数据为:{}", productListVOS);

        return productListVOS;
    }

    @Override
    public List<ProductItemVO> list() {
        log.debug("开始处理[查询商品列表]业务,无参数");
        List<ProductListVO>productList = productMapper.list();
        List<ProductItemVO> list = new ArrayList<>();
        for (ProductListVO item:productList) {

            BrandStandardVO brandStandardVO = brandMapper.getStandardById(item.getBrandId());
            log.debug("根据品牌id【{}】查询到的品牌详情有{}", item.getBrandId(), brandStandardVO);

            CategoryStandardVO categoryStandardVO = categoryMapper.getStandardById(item.getCategoryId());
            log.debug("根据类别id【{}】查询类别详情有{}", item.getCategoryId(), categoryStandardVO);

            List<AttributeTemplateStandardVO> templateList = attributeTemplateMapper.getStandardByProductId(item.getId());
            if (templateList == null) {
                String message = "获取商品属性模板详情失败，id无效！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
            }
            List<String> attributeTemplateNames = new ArrayList<>();
            for (AttributeTemplateStandardVO templateNameItem : templateList) {
                attributeTemplateNames.add(templateNameItem.getName());
            }


            List<Long> attributeTemplateIds = new ArrayList<>();
            for (AttributeTemplateStandardVO templateIdItem : templateList) {
                attributeTemplateIds.add(templateIdItem.getId());
            }
            log.debug("该商品的属性模板id有{}", attributeTemplateIds);
            List<AttributeStandardVO> list1 = attributeMapper.getStandardByTemplateIds(attributeTemplateIds);
            log.debug("根据该商品的属性模板id查询属性完成,数据为:{}", list1);

            List<String> attributeNames = new ArrayList<>();
            for (AttributeStandardVO attributeItem : list1) {
                attributeNames.add(attributeItem.getName());
            }


            log.debug("开始处理根据商品id【{}】查询相册数据",item.getId());
            AlbumStandardVO albumStandardVO = albumMapper.getStandardByProductId(item.getId());
            if (albumStandardVO == null) {
                String message = "获取商品相册详情失败，id无效！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
            }
            List<PictureStandardVO>pictureList = pictureMapper.getStandardByAlbumId(albumStandardVO.getId());
            List<String>pictureUrls = new ArrayList<>();
            for (PictureStandardVO pictureItem:pictureList) {
                pictureUrls.add(pictureItem.getUrl());
            }
            log.debug("根据该商品的相册id查询图片完成,数据为:{}", pictureUrls);


            ProductItemVO productListVOS = new ProductItemVO();
            BeanUtils.copyProperties(item,productListVOS);
            productListVOS.setBrandName(brandStandardVO.getName());
            productListVOS.setCategoryName(categoryStandardVO.getName());
            productListVOS.setAlbumPicture(pictureUrls);
            productListVOS.setAttributeTemplateName(attributeTemplateNames);
            productListVOS.setAttributeName(attributeNames);
            log.debug("商品详情中数据为:{}", productListVOS);

            list.add(productListVOS);
        }
        log.debug("商品列表有:{}",list);
        return list;
    }


}

